package com.crm.system.service.impl.godluck;

import cn.hutool.core.date.DateTime;
import com.crm.common.util.CommonUtils;
import com.crm.common.util.DateUtil;
import com.crm.common.util.DateUtils;
import com.crm.model.entity.cluePoolManager.Clue;
import com.crm.model.entity.godluck.GodLuck;
import com.crm.model.entity.godluck.GodLuckRecord;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.UserInfo;
import com.crm.model.vo.customerManager.CustomerVO;
import com.crm.model.vo.godluck.GodLuckStatisticsVO;
import com.crm.model.vo.godluck.GodLuckVO;
import com.crm.redis.mapper.ValueRMapper;
import com.crm.service.godluck.GodLuckDbService;
import com.crm.service.godluck.GodLuckRecordDbService;
import com.crm.service.sys.UserInfoDbService;
import com.crm.system.service.cluePoolManager.ClueService;
import com.crm.system.service.customerManager.CustomerService;
import com.crm.system.service.godluck.GodLuckService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 首页上上签
 * @Author lixq-f
 * @Date 2021/4/12
 * @Version V1.0
 **/
@Slf4j
@Service
public class GodLuckServiceImpl implements GodLuckService {

    @Autowired
    private GodLuckDbService godLuckDbService;
    @Autowired
    private GodLuckRecordDbService recordDbService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private ClueService clueService;
    @Autowired
    private UserInfoDbService userInfoDbService;

    private static final String GOD_LUCK_KEY_PRE = "crm_godluck_";

    public static final List<Integer> integrals;


    static {
        integrals = Arrays.asList(5, 10, 20, 50, 100);
    }


    /**
     * @Description: 抽取今日上上签
     * @Param: []
     * @Return: com.crm.model.vo.godluck.GodLuckVO
     * @Author: lixq-f
     * @Date: 2021/4/13
     **/
    @Override
    public GodLuckVO getGodLuckOfToday() {

        //获取当前登录人信息
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String key = getKey(userAccount.getAccountId());
        Integer value = ValueRMapper.getRedisObject(redisTemplate, key, Integer.class);
        if (Objects.isNull(value)) {
            ValueRMapper.setRedisObject(redisTemplate, key, 2, 24L, TimeUnit.HOURS);
        } else {
            if (value.equals(0)) {
                return new GodLuckVO();
            }
            value--;
            ValueRMapper.setRange(redisTemplate, key, value, 0);
        }

        Random random = new Random();
        double result = random.nextDouble();
        log.info("random-result:{}", result);
        if (result < 1 / 100.0) {
            //客户
            CustomerVO customer = customerService.selectOneCustomer();
            if (Objects.isNull(customer)) {
                return getWishWords(userAccount.getAccountId());
            }
            String customerId = customer.getCustomerId();
            String customerPoolId = customer.getCustomerPoolId();
            //添加抽取记录
            addGodLuckRecord("34", userAccount.getAccountId(),
                    customerId, null, null);
            return getGodLuckByLuckId("34", customerId, customerPoolId,
                    null, null,null);
        }
        if (result < 5 / 100.0) {
            //积分
            UserInfo userInfo = userInfoDbService.selectUserInfoByUserId(userAccount.getUserId());
            if (Objects.isNull(userInfo)) {
                return getWishWords(userAccount.getAccountId());
            }
            int randNum = random.nextInt(5);
            int integral = integrals.get(randNum);
            UserInfo info = new UserInfo();
            info.setUserId(userInfo.getUserId());
            info.setUpdateTm(DateUtil.getSysDate());
            info.setUpdateUserId(userAccount.getAccountId());
            info.setIntegral(Optional.ofNullable(userInfo.getIntegral()).orElse(0) + integral);
            if (userInfoDbService.updateUserInfoByUserId(info)) {
                addGodLuckRecord("35", userAccount.getAccountId(), null,
                        null, integral);
                return getGodLuckByLuckId("35", null, null,
                        null, null,integral);
            }
        }
        if (result < 8 / 100.0) {
            //线索
            Clue clue = clueService.selectOneClue();
            if (Objects.isNull(clue)) {
                return getWishWords(userAccount.getAccountId());
            }
            String clueId = clue.getClueId();
            String cluePoolPublicId = clue.getCluePoolPublicId();
            addGodLuckRecord("36", userAccount.getAccountId(), null, clueId, null);
            return getGodLuckByLuckId("36", null, null,
                    clueId, cluePoolPublicId,null);
        }

        return getWishWords(userAccount.getAccountId());
    }


    /**
     * 抽取祝福语
     *
     * @param accountId
     * @return
     */
    private GodLuckVO getWishWords(String accountId) {
        String randomId = getRandomId();
        //添加抽取记录
        addGodLuckRecord(randomId, accountId, null, null, null);
        return getGodLuckByLuckId(randomId, null, null, null, null,null);
    }


    /**
     * 获取当前用户有效key
     *
     * @param accountId
     * @return
     */
    private String getKey(String accountId) {
        String ymd = DateUtil.getDate();
        String key = GOD_LUCK_KEY_PRE + ymd + "_" + accountId;
        return key;
    }


    /**
     * 添加抽签记录
     *
     * @param luckId
     */
    private void addGodLuckRecord(String luckId, String accountId,
                                  String customerId, String clueId, Integer integral) {
        GodLuckRecord record = new GodLuckRecord();
        record.setLuckRecordId(CommonUtils.getGUID());
        record.setUserId(accountId);
        record.setLuckId(luckId);
        record.setDeleteStatus((short) 0);
        record.setCreateTm(new Date());
        record.setCustomerId(customerId);
        record.setClueId(clueId);
        record.setIntegral(integral);
        recordDbService.addGodLuckRecord(record);
    }


    /**
     * 获取抽签数据
     *
     * @param luckId
     * @return
     */
    private GodLuckVO getGodLuckByLuckId(String luckId, String customerId, String customerPoolId,
                                         String clueId, String cluePoolPublicId, Integer integral) {
        GodLuckVO resultVO = new GodLuckVO();
        GodLuck godLuck = godLuckDbService.selectGogLuckById(luckId);
        BeanUtils.copyProperties(godLuck, resultVO);
        resultVO.setCustomerId(customerId);
        resultVO.setCustomerPoolId(customerPoolId);
        resultVO.setLuckTypeName(getLuckType(godLuck.getLuckType()));
        resultVO.setClueId(clueId);
        resultVO.setCluePoolPublicId(cluePoolPublicId);
        resultVO.setIntegral(integral);
        return resultVO;
    }


    /**
     * 获取1-20随机概率ID
     *
     * @return
     */
    private String getRandomId() {
        Random random = new Random();
        int randNum = random.nextInt(19) + 1;
        return randNum + "";
    }


    /**
     * 获取抽签类型
     *
     * @param luckType
     * @return
     */
    public String getLuckType(Short luckType) {

        switch (luckType) {
            case 1:
                return "空签";
            case 2:
                return "空签";
            case 3:
                return "空签";
            case 4:
                return "上上签";
            case 5:
                return "上上签";
            case 6:
                return "上上签";
            default:

        }
        return "空签";
    }


    /**
     * @Description: 今日抽签统计
     * @Param: []
     * @Return: com.crm.model.vo.godluck.GodLuckStatisticsVO
     * @Author: lixq-f
     * @Date: 2021/5/14
     **/
    @Override
    public GodLuckStatisticsVO godLuckStatisticsOfToday() {

        GodLuckStatisticsVO statisticsVO = new GodLuckStatisticsVO();
        //获取当前登录人信息
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String key = getKey(userAccount.getAccountId());
        Integer value = ValueRMapper.getRedisObject(redisTemplate, key, Integer.class);
        if (Objects.isNull(value)){
            statisticsVO.setCount(3);
        }else {
            statisticsVO.setCount(value);
        }
        Date date = new Date();
        DateTime begin = DateUtils.beginOfDay(date);
        DateTime end = DateUtils.endOfDay(date);
        List<String> times = recordDbService.getTopThreeByCTime(begin, end);
        Integer numToday = recordDbService.statisticsGodLuckNumToday(begin, end);
        statisticsVO.setImageList(Optional.ofNullable(times).orElse(new ArrayList<>()));
        statisticsVO.setPersonNum(numToday);
        return statisticsVO;
    }


    public static void main(String[] args) {
        Random random = new Random();
        int randNum = random.nextInt(5);
//        System.out.println(count.get());
    }




}
